package com.csx.data.orm.jpa.auto;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.io.resource.Resource;
import com.csx.data.orm.jpa.base.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;

import java.io.InputStreamReader;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * 数据源初始化器
 */
@Component
public class DatabaseInitializer implements CommandLineRunner {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void run(String... args) throws Exception {

        // TODO 需要防止重复初始化数据,因此需要加锁防止多个Pod同时初始化数据
        String lockTableSql = "lock table";

        // 先判断某数据是否存在,如果存在则直接返回
        String tempSql = "select * from user where id = 1";
        List<User> users = jdbcTemplate.query(tempSql, new RowMapper<User>() {
            @Override
            public User mapRow(ResultSet rs, int rowNum) throws SQLException {
                User user = new User();
                user.setFirstName(rs.getString("first_name"));
                user.setLastName(rs.getString("last_name"));
                user.setAge(rs.getInt("age"));
                user.setCity(rs.getString("city"));
                return user;
            }
        });

        if(CollectionUtil.isEmpty(users)) {
            executeInitialize();
        }
    }

    private void executeInitialize() throws Exception{
        Resource resource = new ClassPathResource("scheme.sql");
        String multiSqlStr = FileCopyUtils.copyToString(new InputStreamReader(resource.getStream()));
        String[] sqlArr = multiSqlStr.split(";\r\n");
        for (String sql : sqlArr) {
            // 强制执行 /resource 下面的 scheme.sql
            jdbcTemplate.execute(sql);
        }
    }
}
